//
//  BanBu_EmoManger.m
// Halfarea
//
//  Created by Wang Xj on 14-3-26.
//
//

#import "BanBu_EmoManger.h"
#import "BanBu_EmoMangerCell.h"
#import "BanBu_EmoEditMangerCell.h"
#import "BanBu_PurchaseRecord.h"
#import "BanBu_CollectionController.h"
#import "BanBu_SmileViewAPI.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_DetailEmoViewController.h"
#import "BanBu_ImageView.h"

@interface BanBu_EmoManger ()

@end

@implementation BanBu_EmoManger

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.title = NSLocalizedString(@"emoManger", nil);
    self.tableView.backgroundColor = [UIColor clearColor];
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.view.backgroundColor = [UIColor colorWithPatternImage:img.image];
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self createTableViewHeader];
    [self getEmoInfo];
    [self createEditButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc
{
    [_emoInfoArr release],_emoInfoArr = nil;
    [super dealloc];
}

//设置tableViewHeader
-(void)createTableViewHeader
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 60)];
    view.backgroundColor = [UIColor clearColor];
    view.tag = 1100;
    
    UILabel * textLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 300, 50)];
    textLabel.backgroundColor = [UIColor clearColor];
    textLabel.font = [UIFont systemFontOfSize:16];
    textLabel.textAlignment = UITextAlignmentLeft;
    textLabel.numberOfLines = 1;
    textLabel.text = NSLocalizedString(@"emoEditHints", nil);
    textLabel.tag = 1101;
    
    [view addSubview:textLabel];
    [textLabel release];
    
    self.tableView.tableHeaderView = view;
    
    [view release];
}

-(void)createEditButton
{
    //添加“删除”按钮
    _editButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    _editButton.position = ButtonPositionRight;
    [_editButton.titleLabel setFont:[UIFont systemFontOfSize:16]];
    
    CGFloat btnLen1 = [NSLocalizedString(@"editButton", nil) sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(150, 30)].width;
    _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
    _editButton.tag = 101;
    [_editButton addTarget:self action:@selector(editTable) forControlEvents:UIControlEventTouchUpInside];
    [_editButton setTitle:NSLocalizedString(@"editButton", nil) forState:UIControlStateNormal];
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:_editButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
}

-(void)editTable
{
    [self setEditing:!self.tableView.editing animated:YES];
}
//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
	[super setEditing:!self.editing animated:YES];
    if(self.tableView.editing)
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"finishButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [_editButton setTitle:NSLocalizedString(@"finishButton", nil) forState:UIControlStateNormal];
        
        if (_emoInfoArr.count>0)
        {
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
        }
        else
        {
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
        }
        
        UILabel * textLabel = (UILabel *)[self.tableView.tableHeaderView viewWithTag:1101];
        textLabel.text = NSLocalizedString(@"emoEditingHints", nil);
        textLabel.numberOfLines = 2;
    }
    else
    {
        CGFloat btnLen1 = [NSLocalizedString(@"editButton", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        _editButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        [_editButton setTitle:nil forState:UIControlStateNormal];
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        [_editButton setTitle:NSLocalizedString(@"editButton", nil) forState:UIControlStateNormal];
        
        if (_emoInfoArr.count>0)
        {
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
        }
        else
        {
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
        }
        
        UILabel * textLabel = (UILabel *)[self.tableView.tableHeaderView viewWithTag:1101];
        textLabel.text = NSLocalizedString(@"emoEditHints", nil);
        textLabel.numberOfLines = 2;
    }
    [self.tableView reloadData];
}

//获取已下载的
-(void)getEmoInfo
{
    NSDictionary * downloadEmoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:downloadEmoDic.allValues];
    
    [array sortUsingFunction:compare context:NULL];
    
    self.emoInfoArr = array;
}

//比较，排序
NSComparisonResult compare(NSDictionary *firstDict, NSDictionary *secondDict, void *context)
{
    if ([[firstDict objectForKey:KeyIndex] intValue] < [[secondDict objectForKey:KeyIndex] intValue])
        return NSOrderedAscending;
    else if ([[firstDict objectForKey:KeyIndex] intValue] > [[secondDict objectForKey:KeyIndex] intValue])
        return NSOrderedDescending;
    else
        return NSOrderedSame;
}

//比较，排序
NSComparisonResult compareWithID(NSDictionary *firstDict, NSDictionary *secondDict, void *context)
{
    NSString * first = [firstDict valueForKey:KeyFavid];
    NSString * second = [secondDict valueForKey:KeyFavid];
    
    if (strcmp([first UTF8String], [second UTF8String])<0)
    {
        return NSOrderedAscending;
    }
    else if(strcmp([first UTF8String], [second UTF8String])>0)
    {
        return NSOrderedDescending;
    }
    else
    {
        return NSOrderedSame;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.editing)
    {
        return 1;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return _emoInfoArr.count;
    }
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!indexPath.section)
    {
        return 55;
    }
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        static NSString *CellIdentifier = @"Cell";
        BanBu_EmoEditMangerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BanBu_EmoEditMangerCell" owner:self options:nil] lastObject];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
            cell.backgroundColor = [UIColor clearColor];
        }
        
        NSDictionary * oneEmoInfoDic = [_emoInfoArr objectAtIndex:indexPath.row];
        [cell setAllInfo:oneEmoInfoDic];
        
        return cell;
    }
    else
    {
        static NSString *CellIdentifier = @"emoMangerCell";
        BanBu_EmoMangerCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil)
        {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"BanBu_EmoMangerCell" owner:self options:nil] lastObject];
            
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.selectionStyle = UITableViewCellSelectionStyleBlue;
        }
        
        if (indexPath.row == 0)
        {
            cell.contentLabel.text = NSLocalizedString(@"collectedEmo", nil);
        }
        else if (indexPath.row==1)
        {
            cell.contentLabel.text = NSLocalizedString(@"buyingEmoRecord", nil);
        }
        return cell;
    }
}

#pragma mark - UITableViewDataSource
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1)
    {
        return UITableViewCellEditingStyleNone;
    }
    return UITableViewCellEditingStyleDelete;
}

//实现移动
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSMutableDictionary * downloadEmoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    
    NSDictionary * sourceDic = [[_emoInfoArr objectAtIndex:sourceIndexPath.row] retain];
    
    [_emoInfoArr removeObjectAtIndex:sourceIndexPath.row];
    [_emoInfoArr insertObject:sourceDic atIndex:destinationIndexPath.row];
    
    for (int i = MIN(sourceIndexPath.row, destinationIndexPath.row); i<=MAX(sourceIndexPath.row, destinationIndexPath.row); i++)
    {
        NSMutableDictionary * emoDic = [NSMutableDictionary dictionaryWithDictionary:[_emoInfoArr objectAtIndex:i]];
        [emoDic setValue:[NSNumber numberWithInt:i] forKey:KeyIndex];
        [_emoInfoArr replaceObjectAtIndex:i withObject:emoDic];
        [downloadEmoDic setValue:emoDic forKey:[emoDic valueForKey:Keyid]];
    }
    
    //归档
    [NSKeyedArchiver archiveRootObject:downloadEmoDic toFile:DownloadInfoPath];
    
    [tableView reloadData];
    
    //刷新表情键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshDownloadedEmo object:nil];
}

//实现删除行
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    BanBu_EmoEditMangerCell * cell = (BanBu_EmoEditMangerCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    //从数据源中删除
    NSMutableDictionary * downloadEmoDic = [NSKeyedUnarchiver unarchiveObjectWithFile:DownloadInfoPath];
    
    [downloadEmoDic removeObjectForKey:[cell.emoInfoDic valueForKey:Keyid]];
    
    [NSKeyedArchiver archiveRootObject:downloadEmoDic toFile:DownloadInfoPath];
  
    [_emoInfoArr removeObjectAtIndex:indexPath.row];
    
    //删除table中的行
    [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    
    //刷新表情键盘
    [[NSNotificationCenter defaultCenter]postNotificationName:KRefreshDownloadedEmo object:nil];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==1)
    {
        if (indexPath.row ==1)//表情购买记录
        {
            BanBu_PurchaseRecord * purchaseRecord = [[BanBu_PurchaseRecord alloc]init];
            [self.navigationController pushViewController:purchaseRecord animated:YES];
            [purchaseRecord release];
        }
        else if(indexPath.row == 0)//我收藏的表情
        {
            BanBu_CollectionController *collection = [[BanBu_CollectionController alloc]init];
            [self.navigationController pushViewController:collection animated:YES];
            [collection release];
        }
    }
    else if (indexPath.section == 0)
    {
        BanBu_DetailEmoViewController * detailEmoController = [[BanBu_DetailEmoViewController alloc]init];
        
        detailEmoController.emoInfoDic = [_emoInfoArr objectAtIndex:indexPath.row];
        
        [self.navigationController pushViewController:detailEmoController animated:YES];
        [detailEmoController release];
    }
}

@end
